package cn.shop.dys.fragment;


import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import java.util.ArrayList;
import java.util.List;

import cn.shop.dys.R;
import cn.shop.dys.activity.PayCenterActivity;
import cn.shop.dys.activity.ProductActivity;
import cn.shop.dys.adapter.CartAdapter;
import cn.shop.dys.adapter.GridViewAdapter;
import cn.shop.dys.bean.Cart;
import cn.shop.dys.bean.CartBean;
import cn.shop.dys.bean.CartProInDB;
import cn.shop.dys.bean.CartResp;
import cn.shop.dys.bean.HotProductResp;
import cn.shop.dys.bean.Product;
import cn.shop.dys.bean.ProductProperty;
import cn.shop.dys.constant.CommonConstant;
import cn.shop.dys.constant.DBConstants;
import cn.shop.dys.constant.SPConstant;
import cn.shop.dys.dao.CartDao;
import cn.shop.dys.util.SPUtil;
import cn.shop.lib_common.ComUtils;
import cn.shop.lib_common.CommonUtil;

public class CartFragment extends BaseFragment implements View.OnClickListener, CartAdapter.Callback, AdapterView.OnItemClickListener, CartAdapter.CartIsEmptyListener {

    private List<CartBean> mDatas;
    private CartAdapter mAdapter;
    private String postRequestParamsForBill;
    private List<Product> hotProducts;
    private List<CartBean> selectedGoods;


    private CheckBox cb;
    private TextView tvAccount;
    private GridView gv;
    private TextView tvEdit;
    private ListView lv;
    private RelativeLayout rlBottom;
    private LinearLayout cartEmpty;
    private Button btEmpty;
    private GridViewAdapter mGridViewAdapter;
    private OnUserDetailsClickListener mListener;
    private boolean isCreated;
    private TextView tvCartBuy;

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (!isCreated) {
            isCreated = true;
            mDatas = new ArrayList<>();
            selectedGoods = new ArrayList<>();
            hotProducts = new ArrayList<>();
            initView(view);
        }
    }

    @Override
    public View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_cart, null);
    }

    @Override
    public void onResume() {

        super.onResume();
        //initView(view);
        initData();
        getHotProductFromNet();
        setAdapter();
        setTvAccount();
    }


    @Override
    public void onPause() {
        super.onPause();
        // TODO: 2016/4/24 没启动？
        Log.d("onPause: ", "hahah");
//        if (isEdit) {
//            tvEdit.setText("编辑");
//            for (CartBean cartBean : mDatas) {
//                cartBean.buttonIsVisible = false;
//            }
//        }
        for (CartBean cartBean : mDatas) {
            cartBean.buttonIsVisible = false;
        }
    }

    private void initView(View view) {
        lv = (ListView) view.findViewById(R.id.lv);
        rlBottom = (RelativeLayout) view.findViewById(R.id.rl_bottom);
        cb = (CheckBox) view.findViewById(R.id.cb_all);
        tvAccount = (TextView) view.findViewById(R.id.tv_account);
        tvEdit = (TextView) view.findViewById(R.id.tv_edit);
        tvCartBuy = (TextView) view.findViewById(R.id.tv_cart_buy);

        cartEmpty = (LinearLayout) view.findViewById(R.id.cart_empty);
        btEmpty = (Button) view.findViewById(R.id.bt_empty);
        btEmpty.setOnClickListener(this);
        gv = (GridView) view.findViewById(R.id.gv);

        lv.setEmptyView(cartEmpty);
        lv.setOnItemClickListener(this);
        cb.setOnClickListener(this);
        tvEdit.setOnClickListener(this);
    }

//    private void initAccount() {
//        float mAccount = 0;
//        if (mDatas != null) {
//            for (CartBean cartBean : mDatas) {
//                if (cartBean.isSelected) {
//                    mAccount += cartBean.shopPrice * cartBean.proCount;
//                }
//            }
//        }
//        setTvAccount();
//    }

    /**
     * 设置数据
     */
    public void setAdapter() {
        if (mAdapter == null) {
            mAdapter = new CartAdapter(mContext, mDatas);
            mAdapter.setCartIsEmptyListener(this);
            lv.setAdapter(mAdapter);
            mAdapter.setCallback(this);
        } else {
            mAdapter.notifyDataSetChanged();
            Log.d("test4", mDatas.size() + "");
        }
        if (mDatas.isEmpty()) {
            rlBottom.setVisibility(View.GONE);
        } else {
            rlBottom.setVisibility(View.VISIBLE);
        }

    }

    /**
     * 从服务器获取数据
     */
    private void initData() {

        String requestString = initCartInfoFromDBToString();
        if (TextUtils.isEmpty(requestString)) return;

        mHttpUtils.configDefaultHttpCacheExpiry(0);
        mHttpUtils.configTimeout(10000);
        RequestParams params = new RequestParams();
        params.addBodyParameter("sku", requestString);
        mHttpUtils.send(HttpRequest.HttpMethod.POST, CommonConstant.HOST + "/cart",
                params, new RequestCallBack<String>() {
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
//                        Log.d("test", responseInfo.statusCode + "");
                        if (responseInfo.statusCode == 200) {
                            String json = responseInfo.result;
                            //Log.d("test4", json);
                            CartResp cartResp = mGson.fromJson(json, CartResp.class);
                            if (cartResp != null) {
                                List<Cart> carts = cartResp.cart;
                                mDatas.clear();
                                Log.d("test4", mDatas.toString());
                                for (Cart cart : carts) {
                                    float shopPrice = cart.product.price;

                                    String proImg = CommonConstant.HOST + cart.product.pic;
                                    String proName = cart.product.name;

                                    int proCount = cart.getProdNum();
                                    int proId = cart.product.id;
                                    List<ProductProperty> productProperty = cart.product.productProperty;

                                    int number = Integer.parseInt(cart.product.number);
                                    CartBean cartBean = new CartBean
                                            (shopPrice, proImg, proName, proCount, proId, productProperty, number);
                                    mDatas.add(cartBean);
                                    Log.d("test4", mDatas.toString());

                                }

//                                Log.d("test", mDatas.size() + "");
                                setAdapter();
                            }
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, String s) {
                        // Log.d("test", "访问失败");
                    }
                });

    }

    private String initCartInfoFromDBToString() {
        StringBuilder myCartInfo = new StringBuilder();
        String userId = SPUtil.getString(mContext, SPConstant.USER_INFO_USER_ID);
        List<CartProInDB> cartProInDBs = CartDao.findAll(userId);
//        List<CartProInDB> cartProInDBs = CartDao.findAll(userId);
        Log.d("test4", cartProInDBs.size() + "");
        if (cartProInDBs.isEmpty()) return "";

        for (CartProInDB cartProInDB : cartProInDBs) {
            myCartInfo.append(cartProInDB.getProductId())
                    .append(":")
                    .append(cartProInDB.getProductNum())
                    .append(":");

            String productProperty = cartProInDB.getProductProperty();
            if (!TextUtils.isEmpty(productProperty)) {
                myCartInfo.append(productProperty).append("|");
            }
        }


        // Log.d("test", requestString);
        return myCartInfo.substring(0, myCartInfo.length() - 1);

    }

    @Override
    public void setOnUserDetailsClickListener(OnUserDetailsClickListener listener) {
        this.mListener = listener;
    }

    private boolean isEdit;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.cb_all:
                CheckBox cb = (CheckBox) v;
                if (cb.isChecked()) {
                    mAdapter.selectAll(true);
                } else {
                    mAdapter.selectAll(false);
                }
                setTvAccount();
                break;
            case R.id.bt_empty:
                /*Intent btIntent = new Intent(mContext, MainActivity2.class);
                startActivity(btIntent);*/
                mListener.onClick(1);
                break;
//            case R.id.fab_account:
//                //传入选中的商品数据，String类型
//                if (TextUtils.isEmpty(postRequestParamsForBill)) {
//                    CommonUtil.showToast(mContext, "您还未选择商品，请选择后再结算哦，亲");
//                } else {
//                    String userId = SPUtil.getString(mContext, SPConstant.USER_INFO_USER_ID);
//                    if (TextUtils.isEmpty(userId)) {
//                        userId = "20428";
//                        for (CartBean selectedGood : selectedGoods) {
//                            CartProInDB cartProInDB = new CartProInDB(userId, selectedGood.proId,
//                                    selectedGood.proCount, propropertyListToText(selectedGood.productPropertys));
//                            CartDao.remove(cartProInDB);
//
//                        }
//                        mDatas.removeAll(selectedGoods);
//                        setAdapter();
//                    }
//
//                    //setAdapter();
//                    Intent intent = new Intent(mContext, PayCenterActivity.class);
//                    intent.putExtra(CommonConstant.CART_TO_BILL, postRequestParamsForBill);
//
//                    startActivity(intent);
//                    postRequestParamsForBill = "";
//                }
//                break;

            /**
             * 跳转结算
             */
            case R.id.tv_edit:
                //传入选中的商品数据，String类型
                String userId = SPUtil.getString(mContext, SPConstant.USER_INFO_USER_ID);
                if (TextUtils.isEmpty(userId)) {
                    CommonUtil.showToast(mContext, "您还未登陆");
                    return;
                }

                setPostRequestParamsForBill();
                if (TextUtils.isEmpty(postRequestParamsForBill)) {
                    CommonUtil.showToast(mContext, "您还未选择商品，请选择后再结算哦，亲");
                    return;
                }
//                    if (!TextUtils.isEmpty(userId)) {
//                        userId = "20428";
                // 删除数据
                for (CartBean selectedGood : selectedGoods) {
                    CartProInDB cartProInDB = new CartProInDB(userId, selectedGood.proId,
                            selectedGood.proCount, propropertyListToText(selectedGood.productPropertys));
                    CartDao.remove(cartProInDB);

                }
                mDatas.removeAll(selectedGoods);
                setAdapter();
//                    }

                // 跳转结算
                Intent intent = new Intent(mContext, PayCenterActivity.class);
                intent.putExtra(CommonConstant.CART_TO_BILL, postRequestParamsForBill);
                startActivity(intent);

                // 刷新
                postRequestParamsForBill = "";
                selectedGoods.clear();
                setAdapter();
//                if (isEdit) {
//                    tvEdit.setText("完成");
//                    for (CartBean cartBean : mDatas) {
//                        cartBean.buttonIsVisible = true;
//                    }
//                } else {
//                    tvEdit.setText("编辑");
//                    for (CartBean cartBean : mDatas) {
//                        cartBean.buttonIsVisible = false;
//                    }
//                }
                break;
        }
    }

    /**
     * 编辑菜单调用
     */
    public void cartEdit() {
        isEdit = !isEdit;
        for (CartBean cartBean : mDatas) {
            cartBean.buttonIsVisible = isEdit;
        }
        setAdapter();
    }

    @Override
    public void onColorChange(int color) {
        rlBottom.setBackgroundResource(color);
        tvCartBuy.setBackgroundResource(color);
    }

    @Override
    public void onChecked() {
        cb.setChecked(true);
        setTvAccount();
    }

    /**
     * 设置总计价格
     */
    public void setTvAccount() {
//        vAccount.setText(String.format("%s", mAdapter.getAccount()));
//        String showPrice = ComUtils.getShowPrice(mAdapter.getAccount()).toString();
        SpannableStringBuilder builder = new SpannableStringBuilder();
        SpannableString showText = new SpannableString("总计：");
        showText.setSpan(new ForegroundColorSpan(Color.RED), 0, showText.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        SpannableString showPrice = ComUtils.getShowPrice(mAdapter.getAccount());
        SpannableStringBuilder stringBuilder = builder.append(showText).append(showPrice);
        tvAccount.setText(stringBuilder);
    }

    @Override
    public void onCancel() {
        cb.setChecked(false);
        setTvAccount();
    }

    @Override
    public void onAccountChange() {
        setTvAccount();
    }

//    @Override
//    public void onProductCheckedChanged(List<CartBean> selectedGoods) {
//        StringBuilder settleAccountsString = new StringBuilder();
//        if (selectedGoods != null && selectedGoods.size() > 0) {
//            this.selectedGoods = selectedGoods;
//            for (CartBean selectedGood : selectedGoods) {
//                settleAccountsString.append(selectedGood.proId).append(":")
//                        .append(selectedGood.proCount).append(":");
//                if (selectedGood.productPropertys != null && selectedGood.productPropertys.size() > 0) {
//                    String text = propropertyListToText(selectedGood.productPropertys);
//                    settleAccountsString.append(text).append("|");
//                }
//            }
//            postRequestParamsForBill = settleAccountsString.substring(0, settleAccountsString.length() - 1);
//            Log.d("test", postRequestParamsForBill);
//        } else {
//            postRequestParamsForBill = "";
//        }
//    }

    /**
     * 拼接订单
     */
    private void setPostRequestParamsForBill() {
        postRequestParamsForBill = "";
        if (mDatas.isEmpty()) {
            return;
        }
        StringBuilder settleAccountsString = new StringBuilder();
        for (CartBean cartBean : mDatas) {
            if (cartBean.isSelected) {
                selectedGoods.add(cartBean);
                settleAccountsString.append(cartBean.proId).append(":")
                        .append(cartBean.proCount).append(":");
                if (cartBean.productPropertys != null && cartBean.productPropertys.size() > 0) {
                    String text = propropertyListToText(cartBean.productPropertys);
                    settleAccountsString.append(text).append("|");
                }
            }
        }
        if (selectedGoods.isEmpty()) {
            return;
        }
        postRequestParamsForBill = settleAccountsString.substring(0, settleAccountsString.length() - 1);
        Log.d("test", postRequestParamsForBill);
    }

    /**
     * 拼接属性
     *
     * @param productPropertys
     * @return
     */
    private String propropertyListToText(List<ProductProperty> productPropertys) {
        StringBuilder propropertyText = new StringBuilder();
        if (productPropertys != null && productPropertys.size() > 0) {
            for (ProductProperty productProperty : productPropertys) {
                propropertyText.append(productProperty.getId()).append(",");
            }
            propropertyText.deleteCharAt(propropertyText.length() - 1);
        }
        return propropertyText.toString();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        // TODO: 2016/4/15 跳转商品详情
        //Toast.makeText(mContext, "position:" + position, Toast.LENGTH_SHORT).show();
        Intent intent = new Intent(mContext, ProductActivity.class);
        intent.putExtra("pId", mDatas.get(position).proId);
        mContext.startActivity(intent);
    }

    /**
     * 热门商品
     */
    public void setGridViewAdapter() {
        if (mGridViewAdapter == null) {
            mGridViewAdapter = new GridViewAdapter(mContext, hotProducts);
            gv.setAdapter(mGridViewAdapter);
            gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    // TODO: 2016/4/19 跳转商品详情
                    Intent intent = new Intent(mContext, ProductActivity.class);
                    intent.putExtra("pId", hotProducts.get(position).id);
                    //intent.putExtra("pId",1);
                    mContext.startActivity(intent);
                }
            });
        } else {
            mGridViewAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 获取热门商品
     */
    public void getHotProductFromNet() {

        mHttpUtils.configDefaultHttpCacheExpiry(0);
        mHttpUtils.configTimeout(10000);
        RequestParams params = new RequestParams();
        params.addQueryStringParameter("page", "1");
        params.addQueryStringParameter("pageNum", "6");
        params.addQueryStringParameter("orderby", "saleDown");

        mHttpUtils.send(HttpRequest.HttpMethod.POST, DBConstants.HOTPRODUCT, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                if (responseInfo.statusCode == 200) {
                    String json = responseInfo.result;
                    Log.d("test", json);

                    HotProductResp hotProductResp = mGson.fromJson(json, HotProductResp.class);

                    if (hotProductResp.productList != null) {
                        hotProducts.clear();
                        hotProducts.addAll(hotProductResp.productList);
                    }
                    //Log.d("test", hotProducts.size() + "");
                    setGridViewAdapter();
//                    initGrideViewData(hotProducts);
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
                Log.d("test", "获取失败");
            }
        });

    }

    @Override
    public void onViewGone() {
        rlBottom.setVisibility(View.GONE);
//        tvEdit.setText("编辑");
    }


    @Override
    public void onViewVisible() {
        rlBottom.setVisibility(View.VISIBLE);
    }
}
